package com.beikai.springbootdemo.config.dao;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * @ClassName SessionFactoryConfiguration
 * @Description TODO
 * @Author Admin
 * @Date 2018/11/18 19:38
 * @Version 1.0
 **/
@Configuration
public class SessionFactoryConfiguration {
    @Value("${mybatis_config_file}")
    private String mybatisConfigFilePath;
    @Value("${mapper_path}")
    private String mapper;
    @Value("${entity_package}")
    private String entityPackage;

    @Autowired
    private DataSource dataSource;
    /**
     * 创建sqlSessionFactoryBean 实例 并且设置configtion 设置mapper 映射路径 设置datasource数据源
     * @return
     * @throws IOException
     */
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        // 设置 mybatisconfiguration 的扫描路径  扫描mybatis-config.xml配置文件的路径
        sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFilePath));
        // 设置 mapper的扫描路径
        PathMatchingResourcePatternResolver resolve = new PathMatchingResourcePatternResolver();
        String mapperPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapper;
        sqlSessionFactoryBean.setMapperLocations(resolve.getResources(mapperPath));
        // 设置 DataSource
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 设置实体类路径
        sqlSessionFactoryBean.setTypeAliasesPackage(entityPackage);
        
        return sqlSessionFactoryBean;
    }
}
